package com.example.netty.chatSystem.serializer;

import com.google.gson.Gson;

import java.io.*;
import java.nio.charset.StandardCharsets;

public interface Serializer {
    <T> T deSerializer(Class<T> tClass,byte[] bytes);
    <T> byte[] serializer(T object);

    enum Algorithm implements Serializer{
        java{
            @Override
            public <T> T deSerializer(Class<T> tClass, byte[] bytes) {
                try {
                    ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
                    Object object = objectInputStream.readObject();
                    return (T) object;
                } catch (IOException e) {
                    throw new RuntimeException("反序列化失败",e);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("反序列化失败",e);
                }

            }

            @Override
            public <T> byte[] serializer(T object) {
                try {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                    objectOutputStream.writeObject(object);
                    return byteArrayOutputStream.toByteArray();
                } catch (IOException e) {
                    throw new RuntimeException("序列化失败",e);
                }
            }
        },
        json{
            @Override
            public <T> T deSerializer(Class<T> tClass, byte[] bytes) {
                String s = new String(bytes,StandardCharsets.UTF_8);
                return new Gson().fromJson(s,tClass);
            }

            @Override
            public <T> byte[] serializer(T object) {
                String s = new Gson().toJson(object);
                return s.getBytes(StandardCharsets.UTF_8);
            }
        }
    }
}
